# -*- coding: utf-8 -*-
# flake8: noqa
from qiniu import Auth, put_data, etag, urlsafe_base64_encode
import qiniu.config

# 需要填写你的 Access Key 和 Secret Key
access_key = 'i1WQHW6NDyihAoE1L7fAQxWwhkiHOFwTLImjkAHm'
secret_key = 'j_p5EXwE-wDVKobW3Nq-UYPmzwooQOrmlM6_axDf'
# 构建鉴权对象
q = Auth(access_key, secret_key)
# 要上传的空间
bucket_name = 'aijiazufang'


def avatar_upload(data):
    # 上传到七牛后保存的文件名
    # key = None
    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name)
    # 要上传文件的本地路径
    # def upload(file):
    #     put_data()

    print(token)
    # localfile = './con.ico'
    # with open('./con.ico', 'rb') as f:
    #     data = f.read()

    # 设置none为不制定文件名
    ret, info = put_data(token, None, data)
    # print(info)
    # # assert ret['key'] == key
    # # assert ret['hash'] == etag(localfile)
    # print(ret)
    print(type(info))
    if info.status_code == 200:
        # 保存成功
        file_url = ret.get('key')
        return file_url
    else:
        raise Exception('七牛上传失败')


if __name__ == '__main__':

    with open('./con.ico', 'rb') as f:
        data = f.read()
        file_url = avatar_upload(data)
        print(file_url)
